package com.example.shop.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.shop.db.DBconfig;
import com.example.shop.db.OpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/15.
 */
public class SearchHistoryDao {
    OpenHelper mOpenHelper;

    public SearchHistoryDao() {
        mOpenHelper=OpenHelper.getOpenHelper();
    }
    //增加历史记录
    public void addItem(String title){
        SQLiteDatabase sqLiteDatabase=mOpenHelper.getWritableDatabase();
        sqLiteDatabase.execSQL("insert into "+ DBconfig.TABLE_NAME_SEARCH_HISTOTY+"(title) values(?);",new String[]{title});
        sqLiteDatabase.close();
    }
    //删除历史记录
    public void delItem(String title){
        SQLiteDatabase sqLiteDatabase=mOpenHelper.getWritableDatabase();
        sqLiteDatabase.execSQL("delete from "+ DBconfig.TABLE_NAME_SEARCH_HISTOTY+"where title=?;",new String[]{title});
        sqLiteDatabase.close();
    }
    //获取全部历史记录
    public String[] getAllItems(){
        SQLiteDatabase sqLiteDatabase=mOpenHelper.getWritableDatabase();
        Cursor cursor= sqLiteDatabase.rawQuery("select * from "+DBconfig.TABLE_NAME_SEARCH_HISTOTY,null);
        List<String> datas=new ArrayList<>();
        while(cursor.moveToNext()){
            datas.add(cursor.getString(cursor.getColumnIndex("title")));
        }
        cursor.close();
        sqLiteDatabase.close();
        String[] items=new String[datas.size()];
        for (int i = 0; i <items.length ; i++) {
            items[i]=datas.get(i);
        }
        return items;
    }
}
